#!/usr/bin/env python3

import SocketServer
import os
import sys
import struct
import threading
import pdb
CLIENTS = []
CLIENTSsock = []
weblist = []
socklist = []
def enc(path, key):
    path_ret = ""
    for i in range(0, len(path)):
        a=ord(path[i])
        b=ord(key[i%len(key)])
        path_ret +=chr(a^b)
    return path_ret
 

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

#9999 web
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.conn=None
        CLIENTS.append(self.request)
        weblist.append(self)
        self.no=len(CLIENTS)
        for i in range(len(socklist)):
            cli=socklist[i]
            if cli.conn==None:
                socklist[i].conn=self.request
                self.conn=cli.request
                break
        while True:
            data=""
            try:
                data = self.request.recv(8192)
            except Exception,ex:
                print( ex)
                break
            if data:
              try:
                server_address=self.server.__dict__['server_address']
                data=enc(data, '8')                
                self.conn.sendall(data)
              except Exception,ex:
                print( ex)
                break
            else:
                break
        try:
            self.conn.sendall('end')
        except Exception,ex:
            print( ex)
        self.conn=None
        weblist.remove(self)
        CLIENTS.remove(self.request)

#9998 sock
class ThreadedTCPRequestHandlerSock(SocketServer.BaseRequestHandler):
    def handle(self):
        self.conn=None
        CLIENTSsock.append(self.request)
        socklist.append(self)
        self.no=len(CLIENTS)
        while True:
            data=""
            try:
                data = self.request.recv(8192)
            except Exception,ex:
                print( ex )               
                break
            if data:
              try:
                server_address=self.server.__dict__['server_address']
                data=enc(data, '8')
                self.conn.sendall(data)
              except Exception,ex:
                print( ex )               
                break
            else:
                break
        self.conn=None
        CLIENTSsock.remove(self.request)
        socklist.remove(self)

class server():
 def set_close(self):
    self.server.shutdown()
    self.server.server_close()
 def init(self,HOST,s):
    self.server = ThreadedTCPServer(HOST, s)
    self.server.daemon_threads = True
    server_thread = threading.Thread(target=self.server.serve_forever)
    server_thread.daemon = True
    server_thread.start()


HOST = ("0.0.0.0", 9999)
web=server()
web.init(HOST,ThreadedTCPRequestHandler)
HOST = ("0.0.0.0", 9998)
sock=server()
sock.init(HOST,ThreadedTCPRequestHandlerSock)
if True:
    while True:
        try:
            msg = sys.stdin.readline()
            print( msg)
            if msg=="list\n":
                msg = "Server> " + msg
                sys.stdout.write(msg)
                sys.stdout.flush()
                for cli in weblist:
                    print( cli.request,cli.conn)
                print( 'sock:\n')
                for cli in socklist:
                    print( cli.request,cli.conn)
            
        except KeyboardInterrupt:
            break

web.set_close()
sock.set_close()